/*
 * @lc app=leetcode.cn id=86 lang=java
 *
 * [86] 分隔链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    /**
     * Accepted
    168/168 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 60.06 % of java submissions (40.9 MB)
     */
    public ListNode partition(ListNode head, int x) {
        ListNode dummy = new ListNode(0, head);
        ListNode cur = dummy, last = dummy;
        while (cur.next != null) {
            if (cur.next.val < x) {
                if (last.next == cur.next) {
                    last = last.next;
                    cur = cur.next;
                } else {
                    ListNode tmp = cur.next.next;
                    cur.next.next = last.next;
                    last.next = cur.next;
                    last = last.next;
                    cur.next = tmp;
                }
            } else {
                cur = cur.next;
            }
        }
        return dummy.next;
    }
}
// @lc code=end
